package esqeee.xieqing.com.huangrs.listener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.view.View;

import java.io.File;

import esqeee.xieqing.com.huangrs.action.ActionRunHelper;
import esqeee.xieqing.com.huangrs.library.RuntimeLog;
import esqeee.xieqing.com.huangrs.library.captrue.IntentExtras;
import esqeee.xieqing.com.huangrs.library.image.ScreenCaptruer;
import esqeee.xieqing.com.huangrs.ui.ScreenRequestActivity;
import esqeee.xieqing.com.huangrs.utils.ActivationUtils;

import static android.content.Context.MEDIA_PROJECTION_SERVICE;

public class ActionClickRun implements View.OnClickListener {
    private File action;
    private Context context;

    public ActionClickRun(Context context, File action) {
        this.action = action;
        this.context = context;
    }

    @Override
    public void onClick(View view) {
        // 检查受否有截图的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && ScreenCaptruer.mMediaProjection == null) {
            Intent intent = new Intent(context, ScreenRequestActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            IntentExtras.newExtras()
                    .put("callback", new ActivityResultListener() {
                        @Override
                        public void onActivityResult(int requestCode, int resultCode, Intent data) {
                            if (requestCode == 4364) {
                                if (resultCode == Activity.RESULT_OK) {
                                    MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) context.getSystemService(MEDIA_PROJECTION_SERVICE);
                                    ScreenCaptruer.mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
                                } else {
                                    RuntimeLog.i("获取权限失败，请允许截屏！");
                                }
                            }
                        }
                    })
                    .putInIntent(intent);
            context.startActivity(intent);
            return;
        }
        //((Activity)context).moveTaskToBack(true);
        if (ActivationUtils.isActivation()) {
            new Thread(() -> {
                ActionRunHelper.startAction(view.getContext(), action);
            }).start();
        } else {
            ActivationUtils.showActivationDialog(view.getContext());
        }
    }
}
